package com.study.algorithm.substring;

import java.util.HashMap;
import java.util.Map;

public class MinimumWindowSubstring {
    public static String minWindow(String s, String t) {
        if (s == null || t == null || s.length() == 0 || t.length() == 0 || s.length() < t.length()) {
            return "";
        }
        //统计t中字符出现的次数
        Map<Character, Integer> need = new HashMap<>();
        for (char c : t.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }

        int left = 0, right = 0;  //窗口的左右边界
        int valid = 0;      //窗口中满足need条件的字符个数
        int start = 0, minLen = Integer.MAX_VALUE; //最小子串起始位置和长度
        Map<Character, Integer> window = new HashMap<>(); //记录窗口中字符出现的次数

        while (right < s.length()) {
            char c = s.charAt(right);
            right++;
            //如果当前窗口是t中的字符，更新窗口统计
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1); //窗口中字符出现的次数
                //如果当前窗口中字符满足need中的字符，则valid++
                if (window.get(c).equals(need.get(c))) {
                    valid++;
                }
            }
            //如果满足need中的字符个数等于t中字符的个数，则开始收缩窗口
            while (valid == need.size()) {
                //更新最小子串
                if (right - left < minLen) {
                    start = left; //最小子串的起始位置
                    minLen = right - left; //最小子串的长度
                }
                char d = s.charAt(left);//移除窗口最左边的字符
                left++;
                //如果当前窗口中字符是t中的字符，则valid--
                if (need.containsKey(d)) {
                    if (window.get(d).equals(need.get(d))) {
                        valid--;
                    }
                    window.put(d, window.get(d) - 1);//窗口中字符出现的次数
                }
            }
        }
        return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
    }

    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";
        System.out.println(minWindow(s, t));
    }
}
